﻿using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using RuoVea.Identity.Server;

namespace RuoVea.Identity.Utils;
/// <summary>
/// JWT帮助类
/// </summary>
public class JWTHelper
{
    /// <summary>
    /// 创建token
    /// </summary>
    /// <param name="jWTSetting"></param>
    /// <param name="payload"></param>
    /// <returns></returns>
    public static string CreateJwtToken(JWTSetting jWTSetting,IDictionary<string, object> payload)
    {
        string secret = jWTSetting.IssuerSigningKey;
        IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
        IJsonSerializer serializer = new JsonNetSerializer();
        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
        IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
        var token = encoder.Encode(payload, secret);
        return token;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="jWTSetting"></param>
    /// <param name="payload"></param>
    /// <returns></returns>
    public static string CreateJwtToken(JWTSetting jWTSetting, IDictionary<string, string> payload)
    {
        string secret = jWTSetting.IssuerSigningKey;
        IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
        IJsonSerializer serializer = new JsonNetSerializer();
        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
        IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
        var token = encoder.Encode(payload, secret);
        return token;
    }
    /// <summary>
    /// 校验解析token
    /// </summary>
    /// <returns></returns>
    public static string ValidateJwtToken(string token, string secret)
    {
        try
        {
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtAlgorithm alg = new HMACSHA256Algorithm();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);
            var json = decoder.Decode(token, secret, true);
            //校验通过，返回解密后的字符串
            return json;
        }
        catch (TokenExpiredException)
        {
            //表示过期
            return "expired";
        }
        catch (SignatureVerificationException)
        {
            //表示验证不通过
            return "invalid";
        }
        catch (Exception)
        {
            return "error";
        }
    }
}

